package com.iflyings.android.util

import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream

object FileUtils {

    fun deleteFile(filePath: String) {
        val file = File(filePath)
        if (file.isDirectory) {
            file.listFiles()?.forEach {
                if (it.isDirectory) {
                    deleteFile(it.absolutePath)
                }
                it.delete()
            }
        }
        file.delete()
    }

    fun deleteFileInDir(filePath: String) {
        val file = File(filePath)
        if (file.isDirectory) {
            file.listFiles()?.forEach {
                deleteFile(it.absolutePath)
            }
        }
    }

    fun readString(filePath: String): String {
        FileInputStream(filePath).use {
            val array = ByteArray(it.available())
            check(array.size == it.read(array))
            return String(array)
        }
    }

    fun writeString(filePath: String, content: String) {
        FileOutputStream(filePath).use {
            it.write(content.toByteArray())
        }
    }

    fun findFile(file: File, check: (File) -> Boolean): File? {
        if (file.isFile) {
            if (check(file)) {
                return file
            }
        } else if (file.isDirectory) {
            file.listFiles()?.forEach {
                val next = findFile(it, check)
                if (next != null) {
                    return next
                }
            }
        }
        return null
    }
}
